<script>
// 选择弹窗列表页（选择员工等）
import { defineComponent,onMounted } from 'vue'
import { Search,Close } from '@element-plus/icons-vue'
export default defineComponent({
	name: 'ChooseDialogue'
})
</script>
<script setup>
import {reqMaterialGroupList,reqMaterialList} from '@/api'
import {materialType} from '@/data'
// const props = defineProps({
// 	// 1: 图片 2:视频 3:语音 4:混剪 5:文本, 默认1
// 	type: {
// 		type: Number,
// 		default: 1
// 	},
// })
const props = defineProps({
	isChoose:{
		type:Boolean,
		default: true
	}
})
const type = ref(1)
const refreshPage = ref(true)
const emits = defineEmits(['getChooseData'])
import { toRaw } from '@vue/reactivity';
import { ref,defineExpose } from 'vue'

	const groupList = ref([])
	const groupName = ref('')
const isRefresh = ref(true)
  const page = ref({
    page:1,
    size:18
  })
  const tableData = ref([])
	const updateGroupDialog = ref(null)
	const deleGroupDialogue = ref(null)
	const editPic = ref(null)
	const isShowAddGroupName = ref(false)
	const activeGroupIndex = ref(0)
	const hoverGroupIndex = ref('')
	const creationId = ref('')

  const total = ref(0)
	let tempTableSelectArr = []
	const getUploadImg = (val)=>{
		console.log(val,'1832323asdasd')
		getDataList()
  }
  const changeType=(type)=>{
   getDataAll()
  }
	const handleSelect= (idx) => {
		if (!props.isChoose) {
				var arr = toRaw(tableData.value)
			let temp = arr[idx]
			window.open(temp.url)

			// videoPlayer.value.show(temp.url)
		}else{
			var arr = toRaw(tableData.value)
		let isExist = tempTableSelectArr.includes(arr[idx])
		if (isExist) {
			var obj = arr.find(item=>{
				return item.id == arr[idx].id
			})
			console.log(obj)
			arr.forEach(item=>{
				if (parseInt(item.selectIndex)>parseInt(obj.selectIndex)){
					item.selectIndex = (parseInt(item.selectIndex) - 1 +'').length>1?(parseInt(item.selectIndex) - 1 +''):'0'+(parseInt(item.selectIndex) - 1 +'')
				}
			})
			tempTableSelectArr = tempTableSelectArr.filter(item=>item.id!=arr[idx].id)
			arr[idx].selectIndex = '0'
		}else{
			tempTableSelectArr.push(arr[idx])
			console.log(arr[idx].selectIndex)
			arr[idx].selectIndex = (tempTableSelectArr.length+'').length>1?(tempTableSelectArr.length+''):'0'+(tempTableSelectArr.length+'')
			console.log(arr[idx].selectIndex,'yiui')
		}
		console.log(arr)
		tableData.value = arr
		console.log(tableData.value)
		}
		
	}

	const handleChangegroupName = () => {
		const r = reqMaterialGroupAdd(
			{
				title:groupName.value,
				gs_type:type.value
			}
		)
		getGroupList()
	}
	const getGroupList = async(val) => {
		console.log('asdasaaaaaaaaa')
		

		const { data } = await reqMaterialGroupList({
		gs_type:type.value
		})
		isRefresh.value = false
		groupList._value = data
		isRefresh.value = true
		activeGroupIndex.value = 0
		getDataList()
  }
  const getDataAll = async()=>{
    isRefresh.value = false
   
			const { data } = await reqMaterialGroupList({
			gs_type:type.value,
		
		})
		groupList._value = data
     var json = Object.assign({
			 	creationId:creationId.value,
			group_id:groupList.value[activeGroupIndex.value].id,
			gs_type:type.value,
		},page.value)
		if (json.creationId){
			delete json.groupId
		}
    console.log(json)
		const r = await reqMaterialList(json)
    var arr = []
		r.data.items.forEach(item=>{
			var obj = Object.assign(item,{isSelect:false,hoverIndex:false})
			// obj.
			arr.push(obj)
		})
    tableData._value = arr
    total.value = r.data.count
    getInitCheck(initData)
		isRefresh.value = true
	}
	const getDataList = async(val)=>{
    isRefresh.value = false
    if (val){
      var json = Object.assign({
				creationId:creationId.value,
			group_id:groupList.value[activeGroupIndex.value].id,
			gs_type:type.value,
    },val)
      
    }else{
      console.log('asdasdasda')
      refreshPage.value = false
       var json = Object.assign({
			group_id:groupList.value[activeGroupIndex.value].id,
			gs_type:type.value,
    },page.value)
    
    }
    if (json.creationId){
			delete json.groupId
		}
    console.log(json)
		const r = await reqMaterialList(json)
		var arr = []
		r.data.items.forEach(item=>{
			var obj = Object.assign(item,{isSelect:false,hoverIndex:false})
			// obj.
			arr.push(obj)
		})
		tableData._value = arr
    isRefresh.value = true
    refreshPage.value = true
	}
  // getGroupList()
  getDataAll()





const dialogVisible = ref(false)
const isLoading = ref(true)
const isLoadingSelect = ref(true)
const dialogueName = ref()
const searchVal = ref('')
const title = ref('选择素材')
const nameTitleMap = {
  'staff':'员工',
  'tag':'标签'
}
// 传递过来的数据

const dataList = ref([])

let selectIds = ref([])
let listIds = ref([])
let currentSelectBool = ref([])
const selectData = ref([])
let initData = []
// 选择
const selectAll = ref(false)
const typeshow= ref()
const show = (type1,val)=>{
	if (typeof(val) == 'number'){
		creationId.value = val
		title.value = '查看视频'
	}else{
		initData = val
	}
  
  dialogVisible.value = true;
	type.value = type1
	typeshow.value=type1
	
  
  // if (val) {
  //   selectIds._value = toRaw(val)
  //   console.log(selectIds.value,val,'父页面传递过来的ids,')
  // }
  setTimeout(()=>{
    getDataAll()
  },5)
}

const getInitCheck=(val)=>{
  let arrInit = toRaw(val)
  console.log(arrInit,'sdfasdfsdf')
  let arr = toRaw(tableData.value)
	if (arrInit){
		arrInit.forEach(item1=>{
      var idx = 0
      var obj = arr.find((item,index)=>{
        idx = index
			  return item.id == item1.id && item1.isSelect
      })
      if (obj) {
        obj.isSelect = true
        tempTableSelectArr.push(obj)
        	arr[idx].selectIndex = (tempTableSelectArr.length+'').length>1?(tempTableSelectArr.length+''):'0'+(tempTableSelectArr.length+'')
      }
      console.log(obj,'11111sdfdsafdf')
      })
	}
    
      tableData.value = arr
    
		// if (isExist) {
			
		// 	console.log(obj)
		// 	arr.forEach(item=>{
		// 		if (parseInt(item.selectIndex)>parseInt(obj.selectIndex)){
		// 			item.selectIndex = (parseInt(item.selectIndex) - 1 +'').length>1?(parseInt(item.selectIndex) - 1 +''):'0'+(parseInt(item.selectIndex) - 1 +'')
		// 		}
		// 	})
		// 	tempTableSelectArr = tempTableSelectArr.filter(item=>item.id!=arr[idx].id)
		// 	arr[idx].selectIndex = '0'
		// }else{
		// 	tempTableSelectArr.push(arr[idx])
		// 	console.log(arr[idx].selectIndex)
		// 	arr[idx].selectIndex = (tempTableSelectArr.length+'').length>1?(tempTableSelectArr.length+''):'0'+(tempTableSelectArr.length+'')
		// 	console.log(arr[idx].selectIndex,'yiui')
		// }
		// console.log(arr)
		// tableData.value = arr
		// console.log(tableData.value)
}
const getDataByIds = ()=>{
  switch (dialogueName.value) {
    case 'staff':
      selectData._value = [
        {id:1,name:"21",avatar:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2Fec%2Fca%2Fd8%2Feccad87a334d082b8ff200ae01157e44.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639642180&t=2652a2445af742fc8a4bb6c8e4f18d1e',rbacName:'管理员'},
      ]
    console.log('根据ids获取已选员工列表',selectIds.value,selectData.value)
    isLoadingSelect.value = false
    break;
  }
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}分页请求接口`)
  getDataList()
}
const handleDele  = (index) => {
  const id = selectData.value[index].id
  const json = selectData.value[index]
  const idx = listIds.value.indexOf(id)
  if (idx!=-1){
    currentSelectBool.value[idx] = false
    selectIds.value = selectIds.value.filter((item)=>item!=id)
    selectData.value = selectData.value.filter((item)=>item.id!=id)
  }else{
    selectIds.value = selectIds.value.filter((item)=>item!=id)
    selectData.value = selectData.value.filter((item)=>item.id!=id)
  }
}
const handleSelectChange = (index,isAll) => {
  
  const id = dataList.value[index].id
  const json = dataList.value[index]
    if (isAll==1) {
      if (!selectIds.value.includes(id)){
        selectIds.value.push(id)
        isLoadingSelect.value = true
        selectData.value.push(json)
        isLoadingSelect.value = false
      }
      return
    }
   if (isAll==2) {
    if (selectIds.value.includes(id)){
      selectIds.value = selectIds.value.filter((item)=>item!=id)
      selectData.value = selectData.value.filter((item)=>item.id!=id)
    }
    return
  }
  if (selectIds.value.includes(id)){
    selectIds.value = selectIds.value.filter((item)=>item!=id)
    selectData.value = selectData.value.filter((item)=>item.id!=id)
  }else{
    selectIds.value.push(id)
    isLoadingSelect.value = true
    selectData.value.push(json)
    isLoadingSelect.value = false
  }
  if (currentSelectBool.value.indexOf(false)==-1){
    selectAll.value = true
  }else{
    selectAll.value = false
  }
  isNeedCheckAll()
}
const isNeedCheckAll = ()=>{
   if (currentSelectBool.value.indexOf(false)==-1){
    selectAll.value = true
  }else{
    selectAll.value = false
  }
}
const handleSelectAll = ()=>{
     var arr = toRaw(currentSelectBool.value)
    var selectArr = []
    if (selectAll.value==true){
      arr.forEach((item,index)=>{
        selectArr.push(true)
        handleSelectChange(index,1)
      })
    }else{
      arr.forEach((item,index)=>{
        selectArr.push(false)
        handleSelectChange(index,2)
      })
    }
    isLoading.value = true
    currentSelectBool._value = selectArr
    isLoading.value = false
 
}
let selectMaterial = []
const onSubmit = () => {
  let tempSelectMaterial = []
  let arr = toRaw(tableData.value)
  arr.forEach(item=>{
    if (item.isSelect) {
      tempSelectMaterial.push(item)
    }
  })
  console.log(tempSelectMaterial)
  // for(var i =0;i<tempSelectMaterial.length;i++)
  // {
	// if(tempSelectMaterial[i].gs_type == typeshow.value){
	// 	if(tempSelectMaterial[i].mediaid){

	// 	}else{
	// 		return ElMessage({
	// 				message: '当前资源不可用，请先确定已开通阿里云智能媒体服务，重新上传即可',
	// 				type: 'warning',
	// 			})
	// 	}
	// }else{
	// 		return ElMessage({
	// 				message: '请选择正确格式的数据！',
	// 				type: 'warning',
	// 			})
	// 	}
  // }
  emits('getChooseData', tempSelectMaterial)
  tempTableSelectArr = []
  dialogVisible.value = false;
}
const handleClose = ()=>{
  dialogVisible.value = false;
}
defineExpose({
  show
});
</script>
<template>
  <div v-if="dialogVisible">
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    :width="isChoose?'1050px':'820px'"
    :before-close="handleClose"
  >
  <div class="app-flex-center" v-if="isChoose">
    <div class="app-tab">
			<div @click="type=1;changeType(1)" :class="type==1?'app-tab-item-active':'app-tab-item'">
				图片
			</div>
			<!-- <div @click="type=2;changeType(2)" :class="type==2?'app-tab-item-active':'app-tab-item'">
				视频
			</div>
				<div @click="type=3;changeType(3)" :class="type==3?'app-tab-item-active':'app-tab-item'">
				音频
			</div>
			<div @click="type=4;changeType(4)" :class="type==4?'app-tab-item-active':'app-tab-item'">
				混剪
			</div> -->
		</div>
  </div>

   <div class="pic-main-dia" v-if="isRefresh">
			<div v-if="isChoose" class="pic-main-left-nav app-container-radius">
				<!-- <div class="app-title-underline app-flex-left app-container" @click="isShowAddGroupName=true">
					<MyIcon class="app-icon app-pointer" name="AntDesignPlusSquare" />
					<span class="app-gap-words-left-s app-pointer">添加分组</span>
				</div> -->
				<div class="" v-if="isRefresh">
					<div v-show="isShowAddGroupName" class="app-container-side app-gap-block-top">
						<el-input v-on:keyup.enter="handleChangegroupName" v-model="groupName" maxlength="18" placeholder="输入名称后回车"
							show-word-limit type="text" />
					</div>

					<div class="app-gap-block-top " v-if="isRefresh" :class="isShowAddGroupName?'cell-list-show-input':'cell-list'">
						<div @mouseover="hoverGroupIndex=index"
							@click="activeGroupIndex=index;isShowAddGroupName=false;getDataList();"
							:class="[activeGroupIndex == index?'left-bar-cell-active':'left-bar-cell',hoverGroupIndex==index?'cell-hover':'']"
							v-for="(item,index) in groupList" :key="index">
							<MyIcon class="app-icon file-icon" name="File" />
							<div class="app-flex-2 cell-width">
								<span class="cell-name">{{item.title}}</span>
								<span class="cell-count">{{item.count}}</span>
							</div>
							<!-- <el-popover popper-style="padding: 0px;min-width:0px;" v-if="hoverGroupIndex==index&&index!=0&&index!=1"
								placement="right" :width="100" trigger="hover">
								
								<div class="back-deep">
									<div class="app-hover-cell" @click="showDialog('updateGroup',item)">修改名称</div>
									<div class="app-hover-cell" @click="showDialog('deleGroup',item)">删除分组</div>
								</div>
								<template #reference>
									<div class="cell-more">
										<MyIcon class="app-icon more-icon" name="MoreVertical" />
									</div>
								</template>
							</el-popover> -->
						</div>
					</div>
				</div>
			</div>
			<div class="mater-body app-container-radius" :style="{width:!isChoose?'100%':''}">
				<div class="app-flex-left">
          <span>全部</span>
          <span class="weak-grey-font app-gap-words-left-s app-words-2">共<span class="">{{total}}</span>张{{ isCh0ose?materialType[type]['name']:'视频'}}</span>
           <el-input
      v-model="searchVal"
      class="inp-w280 app-gap-words-left"
      size="large"
      @change="getDataList"
      placeholder="请输入名称"
      clearable
    :suffix-icon="Search"
    />
        </div>
        <div class="inline-module" v-if="isRefresh" >
          <!-- <div class="inline-box">
						<Upload :groupId="groupList[activeGroupIndex].id" @getImg="getUploadImg($event, val)" />
            <div class="inline-title-80 weak-grey-font app-flex-left">
              大小不要超过10.01M<el-popover width="" popper-style="padding: 0px;min-width:0px" placement="top" trigger="hover">
									<div class="app-container">
									图片大小不要超过10.01M,支持图片类型包括 jpg,jpeg,png,gif
									</div>
									<template #reference>
										<MyIcon class="question-icon weak" name="Question" />
									</template>
								</el-popover>
            </div>
          </div> -->
          <div @mouseover="isChoose?item.hoverIndex=true:''" @mouseleave="isChoose?item.hoverIndex=false:''"  class="inline-box" v-for="(item,index) in tableData" :key="index">
          <div class="app-rel" @click="isChoose?item.isSelect=!item.isSelect:'';handleSelect(index)">
            <el-image class="box-80" :src="(type==2||type==4)?item.cover:item.url" fit="contain" />
						<div v-if="item.isSelect&&isChoose" class="app-abs app-pointer check-mask check-mask-80">
							<MyIcon class="check-Center" name="Check" />
							<div class="check-num app-abs" v-if="item.selectIndex!='0'">{{item.selectIndex}}</div>
						</div>
          </div>
            <div class="inline-title-80">
              {{item.name}}
            </div>
            <!-- <div class="app-flex-2 mt-6">
              <span class="weak-grey-font app-words-1">{{item.createTime}}</span>
							<span :style="{visibility:item.hoverIndex||item.isSelect?'':'hidden'}" class="app-primary-font app-words-1 app-pointer">
							<span @click="showDialog('deleGroup', item)">删除</span>
							<span class="app-gap-words-left-xs">|</span>
							<el-popover popper-style="padding: 0px;min-width:0px" 
								placement="top" :width="100" trigger="hover">
								<div>
									<div class="app-hover-cell" @click="showDialog('show',item)">查看</div>
									<div class="app-hover-cell" @click="showDialog('updateGroup',item)">重命名</div>
									<div class="app-hover-cell" @click="showDialog('editPic',item)">裁剪</div>
								</div>
								<template #reference>
									<span class="app-gap-words-left-xs">更多</span>
								</template>
							</el-popover>
							
							</span>
            </div> -->
          </div>
        </div>
      </div>
    </div>
    <Page v-if="refreshPage" :size="18" :page="1" :total="total" @getPage="getDataList($event,val)" />
    <template #footer v-if="isChoose">
      <span class="dialog-footer">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" class="a-s-color-btn" @click="onSubmit"
          >保存</el-button
        >
      </span>
    </template>
	</el-dialog>
	<VideoPlayer ref="videoPlayer" />
  </div>
</template>
<style lang="scss">
	@import url('../../style/app-component.scss');
	@import url('../../style/special.scss');
	@import '../../style/mixin.scss';
	.box-80{
  width: 80px;
  height:80px;
}
.check-mask-80{
	width: 80px !important;
  height:80px !important;
}
.inline-title-80{
	  width: 80px;
  overflow: hidden;
  white-space:nowrap; 
  text-overflow:ellipsis;
}
	.pic-main-dia {
		// height: 400px;
		display: flex;

		.file-icon {
			font-size: var(--app-font-6);
			font-weight: 800;
			color: var(--el-color-primary);
			margin-right: var(--app-block-margin);
		}

		.pic-main-left-nav {
			width: 220px;
			background: var(--app-white-back-color);
			margin-right: var(--app-block-margin);

			.pic-main-left-scroll {
				@include scrollBar;
			}
		}

		.cell-list {
			// height: calc(100vh - 262px - 70px + 80px);
			overflow: auto;
			@include scrollBar;
			overflow: auto;
		}

		.cell-list-show-input {
			// height: calc(100vh - 70px - 262px - var(--app-btn-height) - var(--app-container-padding) + 8px);
			overflow: auto;
			@include scrollBar;
			overflow: auto;
		}

		// table带check的样式


	}


	.mater-body {
		background: var(--app-white-back-color);
		// height: calc(100vh - 70px - 64px - 110px - 22px - 50px + 56px + 92px);
		width: calc(100% - 224px);
    padding: var(--app-container-padding);
    overflow-y:auto;
  	@include scrollBar;
	}
</style>
